package com.seeyon.apps.bense.bank.core;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.nbcb.sdk.OpenSDK;
import com.nbcb.sdk.aes.exception.SDKException;
import com.nbcb.sdk.aes.param.ConfigParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

public class OpenSDKClient {

    private static final Logger log = LoggerFactory.getLogger(OpenSDKClient.class);

    @PostConstruct
    public void initConfig() {
        ConfigParam configParam = new ConfigParam();
        configParam.setPublicUrl(Constants.publicUrl);
        configParam.setPublicKey(Constants.publicKey);
        configParam.setPrivateKey(Constants.privateKey);
        configParam.setAppKey(Constants.appKey);
        configParam.setConnectTimeOut(Integer.valueOf(Constants.connectTimeout));
        configParam.setReadTimeOut(Integer.valueOf(Constants.readTimeout));
        //加载配置  false若配置存在不覆盖，否则覆盖
        try {
            OpenSDK.dynamicInit(configParam, true);
        } catch (SDKException e) {
            log.error("", e);
        }
    }


    public Map<String, Object> sendRequest(String serviceId, Map<String, Object> paramMap) {
        Assert.notNull(paramMap, "参数不能为空");
        paramMap.put("custId", Constants.custId);

        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("Data", paramMap);
        String dataJson = JSONUtil.toJsonStr(requestMap);
        log.info("请求 serviceId【{}】, 参数【{}】", serviceId, dataJson);
        String res = null;
        ConfigParam configParam = new ConfigParam();
        configParam.setPublicUrl(Constants.publicUrl);
        configParam.setPublicKey(Constants.publicKey);
        configParam.setPrivateKey(Constants.privateKey);
        configParam.setAppKey(Constants.appKey);
        configParam.setConnectTimeOut(Integer.valueOf(Constants.connectTimeout));
        configParam.setReadTimeOut(Integer.valueOf(Constants.readTimeout));
        //加载配置  false若配置存在不覆盖，否则覆盖
        try {
            OpenSDK.dynamicInit(configParam, true);
        } catch (SDKException e) {
            log.error("", e);
        }
        try {

            res = OpenSDK.send(configParam.getAppKey(), serviceId, serviceId, dataJson);
            log.info("请求 serviceId【{}】, 返回【{}】,", serviceId, JSONUtil.toJsonStr(res));
        } catch (Exception e) {
            log.error("调用银行系统接口失败, serviceId = {}", serviceId, e);
        }

        Assert.notBlank(res, "调用银行系统接口失败, serviceId = {}", serviceId);
        return JSONUtil.toBean(res, Map.class);
    }
}
